<?php
class Searcher {
	private static $instance;
	private $engines = array();

	public function __construct() {
		$this->loadEngines();
	}

	public static function getInstance() {
		if (self::$instance == null) {
			self::$instance = new Searcher();
		}
		return self::$instance;
	}

	private function loadEngines() {
		$this->engines = array();
		$engines = glob("./engines/*.php");
		foreach ($engines as $engine) {
			include_once $engine;
			$className = strtr($engine,array("./engines/" => "",".php" => "Engine"));
			$this->engines[] = new $className();
		}
	}

	public function getCategories() {
		$html = '';
		$categories = array();
		$this->loadEngines();
		foreach ($this->engines as $engine) {
			foreach ($engine->getTags() as $tag) {
				if (!isset($categories[$tag])) {
					$categories[$tag] = 1;
				} else {
					$categories[$tag]++;
				}
			}
		}
		foreach ($categories as $name => $count) {
			$html .= "<div><a href=\"?t={$name}\">{$name} ({$count})</a></div>";
		}
		return $html;
	}

	public function getSelectedEngines() {
		$tag = isset($_REQUEST['t']) ? $_REQUEST['t'] : 'Web';
		$engines = array();
		foreach ($this->engines as $engine) {
			if (array_search($tag,$engine->getTags()) !== false) {
				$engines[] = $engine;
			}
		}
		return $engines;
	}
	
	public function printSelectedEngines() {
		$html = "Engines: ";
		foreach ($this->getSelectedEngines() as $engine) {
			$html .= $engine->getName() . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		}
		return $html;
	}

	public function search($term) {
		$html = "";
		if (!strlen($term)) return;
		$results = array();
		$res = array();
		foreach ($this->getSelectedEngines() as $engine) {
			$res[] = array_reverse($engine->search($term),false);
			foreach ($res[count($res)-1] as &$r) {
				$r["engineLogo"] = $engine->engineLogo();
			}
		}
		$done = false;
		while (!$done) {
			$done = true;
			foreach ($res as &$r) {
				$elem = array_pop($r);
				if ($elem != NULL) {
					$results[] = $elem;
					$done = false;
				}
			}
		}
		$results = array_slice($results,0,20);
		foreach ($results as $result) {
			$html .= "<div>".$result["engineLogo"]."<a href=\"{$result['href']}\">{$result['title']}</a><br />{$result['description']}</div>";
		}
		return mb_convert_encoding($html, 'UTF-8', mb_detect_encoding($html, 'UTF-8, ISO-8859-1', true));
	}
}
?>